package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Transactional
    public void saveWithdish(SetmealDto setmealDto,int type){
        //储存套餐信息
        this.saveOrUpdate(setmealDto);
        Long id = setmealDto.getId();

        //储存套餐中的菜品信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().forEach((item)->{
            item.setSetmealId(id);
        });
        if(type == 0){
            setmealDishService.saveBatch(setmealDishes);
        }else if(type == 1){
            //删除原来FAVOR表中原数据，重新保存新数据
            LambdaQueryWrapper<SetmealDish>queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(SetmealDish::getSetmealId,id);
            setmealDishService.remove(queryWrapper);
            setmealDishService.saveBatch(setmealDishes);

        }







    }
    @Transactional
    public SetmealDto useIdtodish(Long id){
        Setmeal setmeal = this.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);

        List<SetmealDish> setmealDishes = new ArrayList<>();

        LambdaQueryWrapper<SetmealDish>queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmeal.getId());

        setmealDishes = setmealDishService.list(queryWrapper);

        setmealDto.setSetmealDishes(setmealDishes);

        String name = categoryService.getById(setmeal.getCategoryId()).getName();

        setmealDto.setCategoryName(name);

        return setmealDto;


    }

    @Transactional
    public void delete(Long id){
        Setmeal byId = this.getById(id);

        LambdaQueryWrapper<SetmealDish>queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,id);
        setmealDishService.remove(queryWrapper);

        this.removeById(byId);
    }
}
